package com.augurit.smartform.factory;

import java.io.File;
import java.io.IOException;

import com.augurit.smartform.constant.FreeMarkerConstant;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;

public class FreeMarkerFactory {
	/**
	 * 获得一个FREEMARKER的CONFIGURATION
	 * @param webRealPath
	 * @return
	 * cuigeqiang
	 */
	public static Configuration getConfiguration(String webRealPath){
		Configuration cfg=new Configuration();
		System.out.println(Thread.currentThread().getContextClassLoader().getResource(FreeMarkerConstant.CURRENT_TAGS));
		String tagsPath=Thread.currentThread().getContextClassLoader().getResource(FreeMarkerConstant.CURRENT_TAGS).getPath();						//标签模板放到CLASSES目录下面
		tagsPath = tagsPath.replaceAll("%20", " ");			//把“%20” 替换成空格
		String sourcePath=webRealPath+FreeMarkerConstant.SOURCE;														//JSP模板源文件放到WEBROOT下面
		FileTemplateLoader ftl1=getFileTemplateLoader(tagsPath);
		FileTemplateLoader ftl2=getFileTemplateLoader(sourcePath);
		TemplateLoader[] loaders=new TemplateLoader[]{ftl1,ftl2};
		MultiTemplateLoader mtl=new MultiTemplateLoader(loaders);
		cfg.setTemplateLoader(mtl);
		cfg.setObjectWrapper(new DefaultObjectWrapper());
		cfg.setDateTimeFormat("yyyy-MM-dd hh:mm:ss");
		cfg.setDefaultEncoding("UTF-8");
		return cfg;
	}
	
	/**
	 * 初始化一个FILETEMPLATELOADER
	 * @param filePath
	 * @return
	 * cuigeqiang
	 */
	private static FileTemplateLoader getFileTemplateLoader(String filePath){
		FileTemplateLoader ftl=null;
		try {
			ftl = new FileTemplateLoader(new File(filePath));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ftl;
	}
}
